package demo02;


public class Test01 {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 5;
        myBinarySearch(arr, target);

        String str1 = "abjavacdejavafghijjavakljava";
        countSubString(str1);
        String str2 = "123156456489716123156";
        boolean b = checkString(str2);
        System.out.println(b);
        String sourceString = "ahbgdc";
        String targetString = "abc";
        boolean res = isSubStringOne(sourceString, targetString);
        System.out.println(res);
    }

    private static void myBinarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1); // 修正位运算优先级问题
            if (arr[mid] == target) {
                System.out.println(mid);
                return; // 找到目标值后应立即返回，避免无限循环
            }
            if (arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
    }

    private static boolean checkString(String str) {
        if (str.length() < 5 || str.length() > 15) {
            return false;
        }
        char[] charArray = str.toCharArray();
        for (char c : charArray) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return str.charAt(0) != 0;
    }

    private static void countSubString(String str) {
        String target = "java";
        int count = 0;
        int targetLength = target.length();

        if (str.length() < targetLength) {
            System.out.println(0);
            return;
        }

        // 滑动窗口算法
        for (int i = 0; i <= str.length() - targetLength; i++) {
            if (str.substring(i, i + targetLength).equals(target)) {
                count++;
            }
        }
        System.out.println(count);
    }

    private static boolean isSubStringOne(String sourceString, String targetString) {
        char[] sourceStringCharArray = sourceString.toCharArray();
        char[] targetStringCharArray = targetString.toCharArray();
        int p = 0;
        int q = 0;
        while (p < sourceStringCharArray.length && q < targetStringCharArray.length) {
            if (sourceStringCharArray[p] == targetStringCharArray[q]) {
                q++;
            }
            p++;
        }
        return q == targetStringCharArray.length;
    }
}
